package com.uenpay.im.serializations;

import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.uenpay.im.IMApplication;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.QYXUserEntity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 解析用户资料
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class QYXUserSerializer {

	public static QYXUserEntity deserializeUser(JSONObject json) {
		QYXUserEntity user = new QYXUserEntity();
		user.custid = json.optString("custid");
		user.nickname = json.optString("nickname");
		if (json.has("_nickname")) {
			user.remarkname = json.optString("_nickname");
		}
		user.email = json.optString("email");
		user.realname = json.optString("realname");
		user.pinyinname = json.optString("pinyinname");
		user.birthday = json.optString("birthday");
		user.sex = json.optInt("sex");
		user.mobile = json.optString("mobile");
		user.area = json.optString("area");
		user.idenum = json.optString("idenum");
		user.signature = json.optString("signature");
		user.status = json.optInt("status");
		user.sex = json.optInt("sex");
		user.age = json.optInt("age");
		if (json.has("_isfriend")) {
			user.is_friend = json.optInt("_isfriend");
		}
		if (json.has("_memo")) {
			user.remarkMemo = json.optString("_memo");
		}
		if (json.has("_phonenumber")) {
			user.remarkPhonenumber = json.optString("_phonenumber");
		}

		if (user.custid.equals(IMApplication.getCustId())) {
			IMApplication.config.setUserSignature(user.signature);
			if (json.has("dynamicsetting")) {
				JSONObject dynamicBgJsonObject = json
						.optJSONObject("dynamicsetting");
				if (dynamicBgJsonObject != null) {
					if (dynamicBgJsonObject.has("bgfilehash")
							&& dynamicBgJsonObject.has("bgfileid")) {
						String fileid = dynamicBgJsonObject
								.optString("bgfileid");
						String filehash = dynamicBgJsonObject
								.optString("bgfilehash");

						HttpStreamCache.getInstance().ClearCacheBitmap(
								APIConfiguration.getFileDownloadPath(fileid,
										filehash));
						IMApplication.config.setDynamicBg(APIConfiguration
								.getFileDownloadPath(fileid, filehash));
					}
				}
			}
		}

		return user;
	}

	public static ArrayList<QYXUserEntity> deserializeUsers(JSONArray json) {
		ArrayList<QYXUserEntity> users = new ArrayList<QYXUserEntity>();
		for (int i = 0; i < json.length(); i++) {
			users.add(deserializeUser(json.optJSONObject(i)));
		}
		return users;
	}
}
